﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Write.Applications.Commands.User;
using AutoMapper;
using MediatR;

namespace AuthCenter_API.Write.Applications.CommandHandlers.User
{
    public class UpdUserCommandHandler : IRequestHandler<UpdUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;

        public UpdUserCommandHandler(IBaseRepository<UserModel> userRepository, IMapper mapper)
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }

        public Task<APIResult<object>> Handle(UpdUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.UpdSuccess;
            result.Message = APIEnum.UpdSuccess.Desc();
            var user = _mapper.Map<UserModel>(request);
            user.Password = "123456";
            user.CreateName = "张三";
            user.CreateTime = DateTime.Now;
            user.UpdateName = user.UserName;
            user.UpdateTime = DateTime.Now;
            var exist = _userRepository.GetAll().Any(x => x.UserName == request.UserName && x.Id != request.Id);
            if (exist)
            {
                result.Code = APIEnum.UpdFail;
                result.Message = APIEnum.UpdFail.Desc() + "名称不能重复，请重新输入";
                return Task.FromResult(result);
            }
            _userRepository.Update(user);
            return Task.FromResult(result);
        }
    }
}
